package com.qili.core.quartz.CustomQuartz;

import cn.hutool.core.util.IdUtil;
import com.qili.entity.affaircase.AffairCase;
import com.qili.entity.supervisor.ProjectNotice;
import com.qili.entity.supervisor.SupervisorProject;
import com.qili.entity.supplier.SupplierProject;
import com.qili.entity.supplier.SupplierProjectAccept;
import com.qili.entity.supplier.SupplierProjectPubNotice;
import com.qili.entity.supplier.dto.SupplierProjectPubNoticeDTO;
import com.qili.redis.RedisService;
import com.qili.service.SysUserService;
import com.qili.service.supervisor.ProjectNoticeServie;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.supplier.SupplierProjectPubNoticeService;
import com.qili.util.DateUtil;
import com.qili.util.StringUtil;
import lombok.extern.java.Log;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaoyongke
 * @date 2021/4/7
 * @description 公示期结束发送消息job
 */

@Log
public class GsSendNoticeJob implements Job {
    @Autowired
    SysUserService sys;
    @Autowired
    private SupplierProjectPubNoticeService supplierProjectPubNoticeService;
    @Autowired
    private ProjectNoticeServie projectNoticeServie;
    @Autowired
    private SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    private SupplierProjectAcceptService supplierProjectAcceptService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("GsSendNoticeJob：启动任务=======================");

        log.info("GsSendNoticeJob=======开始==================================");
        String lockkey = "GsSendNoticeJob_key";
        String uuId = IdUtil.simpleUUID();
        try {
            lock(lockkey, uuId);
            run();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            unlock(lockkey, uuId);
        }
    }

    public void run() {
        try {
            // 供需  ----公示期设置定时任务，公示期结束后下午17:30给中标应接人/中标组织发送信息，无论中标与否都需要在待办事宜的站内信提醒。

            SupplierProjectPubNoticeDTO dto = new SupplierProjectPubNoticeDTO();
            List<SupplierProjectPubNoticeDTO> list = supplierProjectPubNoticeService.selectGsSendList(dto);
            for (int i = 0; i < list.size(); i++) {
                SupplierProjectPubNotice supplierProjectPubNotice = list.get(i);
                String supProjectId = supplierProjectPubNotice.getSupProjectId();
                SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
                //恭喜您中标XXX项目 / 很遗憾您应接的XXX项目未中标，请及时查看：点击进入供需详情
                //给中标人发
                sendNoticeToZb(project);
                sendNoticeToNotZb(project);

            }
            System.out.println("JobDemo1：执行完毕=======================");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * @param project
     * @Author:zhaoyongke
     * @Description: 发送给中标人
     * @Date:14:30 2021/4/7
     */
    public void sendNoticeToZb(SupplierProject project) {
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(project.getSupProjectId());
        notice.setIsView("0");
        notice.setSendTo(project.getZbBy());
        notice.setTitle("恭喜您中标" + project.getProjectName() + "项目，请及时查看");
        notice.setNoticeType("101");// 公示结束 发送消息
        notice.setApplicantType("002");// 供需
        notice.setCreateDate(DateUtil.getCurrentDateString());
        projectNoticeServie.insertSelective(notice);
    }


    /**
     * @param project
     * @Author:zhaoyongke
     * @Description: 发送给未中标人
     * @Date:14:30 2021/4/7
     */
    public void sendNoticeToNotZb(SupplierProject project) {
        Example ecj = new Example(SupplierProjectAccept.class);
        Example.Criteria ccj = ecj.createCriteria();
        ccj.andNotEqualTo("isZb", "1");
        ccj.andEqualTo("supProjectId", project.getSupProjectId());
        List<SupplierProjectAccept> list = supplierProjectAcceptService.selectByExample(ecj);
        for (int i = 0; i < list.size(); i++) {
            SupplierProjectAccept accept = list.get(i);
            String acceptBy = accept.getAcceptBy();
            ProjectNotice notice = new ProjectNotice();
            notice.setLinkId(project.getSupProjectId());
            notice.setIsView("0");
            notice.setSendTo(acceptBy);
            notice.setTitle("很遗憾您应接的" + project.getProjectName() + "项目未中标，请及时查看");
            notice.setNoticeType("101");// 公示结束 发送消息
            notice.setApplicantType("002");// 供需
            notice.setCreateDate(DateUtil.getCurrentDateString());
            projectNoticeServie.insertSelective(notice);
        }

    }

    public void lock(String key, String uuId) {
        for (; ; ) {
            boolean r = stringRedisTemplate.opsForValue().setIfAbsent(key, uuId);
            stringRedisTemplate.expire(key, 600, TimeUnit.SECONDS);

            if (r) {
                return;
            } else {
                throw new RuntimeException("已经存在的执行程序...");
            }
        }
    }

    public void unlock(String key, String uuId) {
        if (uuId.equals(stringRedisTemplate.opsForValue().get(key))) {
            stringRedisTemplate.delete(key);
        }
    }

}
